<?php
/**
 * 描述
 * Created by Paco
 * Date: 2018/11/19 Time: 18:40
 */

namespace App\Lib\Utils;

use App\Models\Order\OrderCart;
use App\Traits\ApiRespond;
use Illuminate\Support\Facades\DB;

class Cart
{
    use ApiRespond;
    /**
     * 购物车类
     * 功能：
     * 添加商品
     * 删除商品
     * 商品列表
     * 查看商品
     * 商品+1
     * 商品-1
     * 商品种类
     * 商品个数
     * 商品小计
     */

    protected static $ins = null;
    protected $basket;
    protected $user_id;

    protected function __construct()
    {

    }

    protected static function getIns()
    {
        if (self::$ins == null) {
            self::$ins = new self();
        }
        return self::$ins;
    }

    /**/
    public static function getCar($user_id = 0)
    {
        $basket = app('phpredis')->get('cart_' . $user_id);
        $basket = unserialize($basket);
        if (!$basket) {
            //获取数据表的数据
            if ($user_id) {
                $basket = OrderCart::query()->where('user_id', $user_id)->get()->toArray();
            }
        }
        $cart = self::getIns();
        $cart->user_id = $user_id;
        $cart->basket = $basket;
        return $cart;
    }

    /**
     * 添加商品
     */
    public function addItems($product_id, $sku_id = 0, $quantity = 1)
    {
        $key = $product_id . '_' . $sku_id;
        if (!$this->hasItems($product_id, $sku_id)) {

            $this->basket[$key] = [
                'product_id' => $product_id,
                'quantity' => $quantity,
                'user_id' => $this->user_id,
                'sku_id' => $sku_id,
            ];

        } else {
            $this->basket[$key]['quantity'] += $quantity;
        }

        $this->saveCart();
    }

    /**
     * 删除一种商品
     */
    public function delItems($product_id, $sku_id)
    {
        if ($this->hasItems($product_id, $sku_id)) {
            unset($this->basket[$product_id . '_' . $sku_id]);
            $this->saveCart();
        }
    }

    protected function hasItems($product_id, $sku_id)
    {
        return array_key_exists($product_id . '_' . $sku_id, $this->basket);
    }

    /**
     * 列出商品
     */
    public function listItems()
    {
        return $this->basket;
    }

    /**
     * 清空购物车
     */
    public function clear()
    {
        $this->basket = [];
        $this->saveCart();
    }

    /**
     * 计算商品种类
     */
    public function cnt()
    {
        return count($this->basket);
    }

    /**
     * 计算商品个数
     */
    public function getCount()
    {
        $count = 0;
        if (empty($this->basket)) {
            return $count;
        }
        foreach ($this->basket as $v) {
            $count += $v['quantity'];
        }
        return $count;
    }


    /**
     * 修改商品数量
     */
    public function upItems($product_id, $sku_id, $quantity)
    {
        $key = $product_id . '_' . $sku_id;
        if (!$this->hasItems($product_id, $sku_id)) {
            $this->throwRespondError(10109);
        } else if ($this->basket[$key]['quantity'] <= 0) {
            $this->delItems($product_id, $sku_id);
        } else {
            $this->basket[$key]['quantity'] = $quantity;
        }
        $this->saveCart();
    }

    /**
     * 商品数量+1
     */
    public function addOne($product_id, $sku_id)
    {
        if (!$this->hasItems($product_id, $sku_id)) {
            $this->throwRespondError(10109);
        } else {
            $this->basket[$product_id . '_' . $sku_id]['quantity'] += 1;
            $this->saveCart();
        }
    }

    /**
     *
     * 商品数量减1
     * author Paco
     * createTime 2018/11/20 10:49
     * @param $product_id
     * @param $sku_id
     * @return string
     */
    public function delOne($product_id, $sku_id)
    {
        $key = $product_id . '_' . $sku_id;
        if (!$this->hasItems($product_id, $sku_id)) {
            $this->throwRespondError(10109);
        } else {
            $this->basket[$key]['quantity'] -= 1;
            if ($this->basket[$key]['quantity'] <= 0) {
                $this->basket[$key]['quantity'] = 1;
            }
            $this->saveCart();
        }
    }


    /**
     *
     * 同步内容到数据库（小程序熄屏后请求）
     * author Paco
     * createTime 2018/11/20 12:18
     */
    public function syncCart()
    {
        DB::beginTransaction();
        try {
            OrderCart::query()->where('user_id', $this->user_id)->delete();
            OrderCart::query()->insert($this->basket);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            $this->throwRespondError(10108);
        }
    }


    private function saveCart()
    {
        app('phpredis')->setex('cart_' . $this->user_id, 7200, serialize($this->basket));
    }


}